package com.javaspeak.designpatterns.go4.behavioural.iterator;


/**
 * Provides an implementation of the SnapshotIterator
 *
 * @author John Dickerson
 *
 * @param <E> The object we wish to iterate through
 */
public class SnapshotIteratorImpl<E> implements SnapshotIterator<E> {

    private LinkedElement<E> linkedElement;


    /**
     * Constructor
     * <p>
     * The LinkedElement passed through this constructor is the first
     * LinkedElement that was added by a user. It is
     * also the element that is at the end of the chain of LinkedElements.
     * <p>
     * As new elements are added at the beginning of the chain of
     * LinkedElements, this last LinkedElement in the chain represents the
     * first element that was added to the ConcurrentLinkedList.
     * <p>
     * To navigate through the linkedElements the field previousLinkedElement
     * is used in the LinkedElements.
     *
     * @param last element in the linkedElement chain
     */
    public SnapshotIteratorImpl( LinkedElement<E> linkedElement ){

        this.linkedElement = linkedElement;
    }


    /* (non-Javadoc)
     * @see com.javaspeak.designpatterns.go4.behavioural.iterator.
     *      SnapshotIterator#hasNext()
     */
    @Override
    public boolean hasNext() {

        if (linkedElement !=  null ){
            return true;
        }
        return false;
    }


    /* (non-Javadoc)
     * @see com.javaspeak.designpatterns.go4.behavioural.iterator.
     *      SnapshotIterator#next()
     */
    @Override
    public E next() {

        // as the
        E objectToReturn;

        if ( linkedElement != null ){

            objectToReturn = linkedElement.object;
            linkedElement = linkedElement.previousLinkedElement;
            return objectToReturn;
        }

        return null;
    }
}
